<?php
class PublicAction extends CommonAction {
    public $weixin;
    public function _initialize() {
		$this->initCommon();
        //parent::_initialize();
        Vendor('Weixin.Weixin');
        $d['token'] = getSysVal('token');
        $d['appid'] = getSysVal('appid');
        $d['appsecret'] = getSysVal('appsecret');
        $this->weixin = new WeixinChat($d);
    }
    //会员注册页面
    public function signin() {
		$this->timeout = 5;
        $this->display();
    }
    //会员注册
    public function dosignin() {
		if($_POST['tel']&&$_POST['password']){
			$memberDB=D('Member');
			$groupdb = M('Member_group');
			
			$_POST['site_id']=__SITEID__;
			$pwd = $_POST['password'];
			$_POST['password'] = md5($_POST['password']);
			$_POST['username'] = $_POST['tel'];
			//验证用户的验证码
			$vali['verifycode'] = $_POST['vali'];
			$vali['VerifyPhone'] = 0;
			$vali['tel'] = $_POST['tel'];
			$vali['site_id'] = __SITEID__;
			$memberInfo = $memberDB -> where($vali) -> find();
			//F('sql', $memberDB -> getLastSql());
			if(!$memberInfo){
				//暂时不验证手机
				//$this->success('不验证手机号码！'); exit;
				$this -> error('验证码错误！');exit;
			}
			//找到这个用户的邀请分组
			$group['InvitationCode']  =  $_POST['InvitationCode'];
			if($group == ''){
				$this->error('邀请码错误！');exit;
			}else{
				$groupinfo = $groupdb -> where($group) -> find();
				if(!$groupinfo){
					$this->error('邀请码错误或者不存在！');exit;
				}
			}
			if($_POST['memberCode']){
				$memberinfo=$memberDB->where('InvitationCode='.$_POST['memberCode'])->find();
				if(!$memberinfo){
					$this->error('邀请码错误或者不存在！');exit;
				}
			}
			
			if (session('jumpurl')) {
				$this->assign('jumpUrl',session('jumpurl'));
				$jumpUrl = session('jumpurl');
				session('jumpurl',NULL);
			} else {
				$this->assign('jumpUrl',U('Index/index'));
				$jumpUrl = U('Intesys/Index/index');
			}
			if ($memberDB->create($data)) {
				$savedata = array(
				    'VerifyPhone' => 1, 
					'verifycode' => '', 
					'username' => $_POST['tel'], 
					'password' => $_POST['password'],
					'reg_time' => time()
				);
				$result =$memberDB -> where($vali) -> data($savedata) -> save();
				if (false !== $result) {
					
					//分配权限
					$member_role_userdb = M('Member_role_user');
					$role_user['user_id'] = $memberInfo['id'];
					$role_user['role_id'] = $groupinfo['id'];
					$member_role_userdb -> add($role_user);
					
					//分配部门职位
					if(isset($_POST['gid']) && intval($_POST['gid']) > 0){
						$groupdata['group_id'] = M('Member_group')->where(['invitationCode'=>$_POST['code']])->getField('id');
						if($groupdata['group_id']){
							$r['user_id']= $memberInfo['id'];
							$r['site_id']=__SITEID__;
							$r['role_id']=$groupdata['group_id'];
							$member_role_userdb->add($r);
						}
						$groupdata['memberpositionid'] = ','.intval($_POST['gid']).',';
						$groupdata['memberpositionname'] = M('Member_position') -> where("id='".intval($_POST['gid'])."'") -> getField('name');
					    //$groupdata['memberpositionname'] = implode(',', $val);
						$memberDB -> where(array('id' => $memberInfo['id'])) -> data($groupdata) -> save();
					}
					//确定上级人员
					if(isset($_POST['pid']) && intval($_POST['pid']) > 0){
						$memberDB -> updatePid($memberInfo['id'], intval($_POST['pid']));
					}
					//登录
					import ( '@.ORG.RBACM' );
					$authInfo = RBACM::authenticate ( array('id' => $memberInfo['id']) );
					session('memberInfo', $memberInfo);
					$model=$memberDB;
					$model->find($authInfo ['id']);
					$model->login_time=time();
					$model->login_ip=get_client_ip();
					$model->accesslist=serialize(RBACM::getAccessList($authInfo ['id']));
					$model->save();
					session ( C ( 'USER_AUTH_KEY' ), $authInfo ['id'] );
					session ( 'loginUserName', !empty($authInfo ['username'])?$authInfo ['username']:$authInfo['username'] );
					session ( 'login_count', 0 );
					if($authInfo['isadministrator']==1){
						session ( C ( 'ADMIN_AUTH_KEY' ), true );
					}
					RBACM::saveAccessList();
					$this->success('保存成功！',$jumpUrl);
				} else {
					$this->error($memberDB->getError());
				}
			} else {
				$this->error($memberDB->getError());
			}
		}
		
		
    }
    //会员登录
    public function login() {
        if($this->memberInfo){
            redirect(U('Intesys/Index/index'));
        } else {
            if ($this->is_weixin() && $this->siteInfo['is_wxLogin'] > 0) {
				if($this->siteInfo['is_wxLogin'] == 1){
					$snsapi_base = 1;
				}elseif($this->siteInfo['is_wxLogin'] == 2){
					$snsapi_base = 0;
				}
				
				/*$domain = explode(',', $this->siteInfo['domain']);
				if($domain[0] == ''){
					$domain = C('DOMAIN_MAIN');
				}*/ 
				
                $this->weixin->redirectGetOauthCode('http://' . $_SERVER['HTTP_HOST'] . __APP__ . "/Intesys/Public/getcode.html", $snsapi_base, intval($_COOKIE['aff_id']).'_and_'.base64_encode(session('jumpurl')));
            }
            if ($this->_get('type')) {
                $str = $this->createloginid();
                //echo $str;
				//写一个缓存，5分钟内有效，以便微信回调时确认是哪个站点的扫码事件
				MCS(md5($str), __SITEID__); 
                setcookie('spwd', md5($str) , time() + 1800, '/');
                $tiket = $this->weixin->createQrcode($str);
                $this->assign('tiket', $tiket);
				$this->InvitationCode = $_GET['code'];
            } else {
                redirect(U('Intesys/Public/login', array(
                    'type' => '1'
                )));
            }
        }
        $this->display();
    } 
    private function createloginid() {
		//$time = microtime_float() * 10000;
        $str = rand(100000, 999999);
        $ret = M('Member')->where(array(
            'site_id' => __SITEID__,
            'loginid' => md5($str)
        ))->find();
        if (is_array($ret)) {
            $this->createloginid();
        }
        return $str;
    }
    //会员登出
    public function logout() {
        session(C('ADMIN_AUTH_KEY'),NULL);
        session(C('USER_AUTH_KEY'),NULL);
        session('memberInfo',NULL);
        $this->success('退出成功',U('Public/login'));
    }
    //会员登录验证
    public function doLogin() {
        /*if (!$this->check_verify($this->_post('verify') , 'mycms')) {
            session('mycms','');
            $this->error('验证码错误！');
        }*/
		//用户处于登录状态，并且是站点创始人，直接登录
        if (($this->_post('password') && $this->_post('username')) || ($this->memberInfo && $this->memberInfo['id'] == $this->siteInfo['member_id'])) {
			
            $map['password'] = md5($this->_post('password'));
            $map['_logic'] = 'and';
            $map['site_id'] = __SITEID__;
            $map['username'] = $this->_post('username');
            $map['status']=array('not in',array('0','-1'));//禁用或离职 不能登录
			
			if($this->memberInfo['id'] == $this->siteInfo['member_id']){
				$map['password'] = $this->memberInfo['password'];
                $map['site_id'] = __SITEID__;
                $map['username'] = $this->memberInfo['username'];
			}
            $memberModel = D('Member');
            if ($memberModel->checkLogin($map)) {
                session('memberInfo', $memberModel->userInfo);
                //跳转到认证前页面
                if (session('jumpurl')) {
                    $this->assign('jumpUrl',session('jumpurl'));
                    $url = session('jumpurl');
                    session('jumpurl',NULL);
                } else {
                    $this->assign('jumpUrl',U('Index/index'));
                    $url = U('Intesys/Index/index');
                }
                //RBAC 记录当前用户信息 ！important
                import ( '@.ORG.RBACM' );
                
                $authInfo = RBACM::authenticate ( $map );
                if (! $authInfo) {
                    $this->error ( '登录错误：账户不存在或账户已被禁用！' );
                }
                $model=M('Member');
                $model->find($authInfo ['id']);
                $model->login_time=time();
                $model->login_ip=get_client_ip();
                if(isset($_POST['deviceId'])&&$_POST['requestType']==1){
                    //保存当前用户登录app的唯一标识符
                    $model->loginapp=md5($_POST['deviceId']);
                }
                $model->accesslist=serialize(RBACM::getAccessList($authInfo ['id']));
                $model->save();
                session ( C ( 'USER_AUTH_KEY' ), $authInfo ['id'] );
                session ( 'loginUserName', !empty($authInfo ['username'])?$authInfo ['username']:$authInfo['username'] );
                session ( 'login_count', 0 );
				if($authInfo['isadministrator']==1){
					session ( C ( 'ADMIN_AUTH_KEY' ), true );
				}
                RBACM::saveAccessList();
                //dump(RBACM::getAccessList($authInfo ['id']));
				//dump($model->where(['id'=>$authInfo ['id']])->find());exit;
                
                    //$this->success('登录成功', $url);    
                    redirect(U('Intesys/Index/index'));
                    exit();
                
            } else {
                $this->error($memberModel->loginError);
            }
        } else {
            $this->error('请输入用户和密码');
        }
    }
    //微信扫描登录
    public function weixinDoLogin() {
        if ($this->_post('pass')) {
            if ($_COOKIE['spwd'] == '') {
                $this->error('登录参数出错');
                exit();
            }
            $db = D('Member');
            $ret = $db->where(array(
                'site_id' => __SITEID__,
                'loginid' => $_COOKIE['spwd']
            ))->find();
			
			
		
			
            if (is_array($ret)) {
                //$this->success('登录成功');
                setcookie('spwd', NULL);
                $db->where(array(
                    'site_id' => __SITEID__,
                    'openid' => $ret['openid']
                ))->data(array(
                    'loginid' => ''
                ))->save();
                $map['_logic'] = 'and';
                $map['site_id'] = __SITEID__;
                $map['openid'] = $ret['openid'];
                $memberModel = D('Member');
                if ($memberModel->checkLogin($map)) {
                    session('memberInfo', $memberModel->userInfo);
                    //跳转到认证前页面
                    if (session('jumpurl')) {
                        //$this->assign('jumpUrl',session('jumpurl'));
                        $url = session('jumpurl');
                        session('jumpurl',NULL);
                    } else {
                       
                            $url = U('Index/index');

                    } 
					
					//F('ws', $ret['id']. '---' .$_GET['pid']);
					
					
					//存在推荐码
					$groupdb = M('Member_group');
					//找到这个用户的邀请分组
					$group['InvitationCode']  =  $_POST['InvitationCode'];
					if($group == ''){
						$this->error('邀请码错误！');exit;
					}else{
						$groupinfo = $groupdb -> where($group) -> find();
						if(!$groupinfo){
							$this->error('邀请码错误或者不存在！');exit;
						}
					}
					
					//用户没有权限分配时，根据推荐码对应权限分配
					if($groupinfo){
						$group = $groupdb -> where(array('user_id' => $ret['id'], 'role_id' => $groupinfo['id'])) -> find();
						if(!$group){
							$member_role_userdb = M('Member_role_user');
							$role_user['user_id'] = $ret['id'];
							$role_user['role_id'] = $groupinfo['id'];
							$member_role_userdb -> add($role_user);
						}
					}
					//分配部门职位
					if(isset($_POST['gid']) && intval($_POST['gid']) > 0){
						$groupdata['group_id'] = intval($_POST['gid']);
						$groupdata['memberpositionid'] = ','.intval($_POST['gid']).',';
						$groupdata['memberpositionname'] = M('Member_position') -> where("id='".$groupdata['memberpositionid']."'") -> getField('name');
						$memberModel -> where(array('id' => $ret['id'])) -> data($groupdata) -> save();
					}
					//确定上级人员
					if(isset($_POST['pid']) && intval($_POST['pid']) > 0){
						$memberModel -> updatePid($ret['id'], intval($_POST['pid']));
						
					} 
					
					
					
                    //RBAC 记录当前用户信息 ！important
                    import ( '@.ORG.RBACM' );
                    
                    $authInfo = RBACM::authenticate ( $map );
                    if (! $authInfo) {
                        $this->error ( '登录错误：账户不存在或账户已被禁用！' );
                    }
                    $model=M('Member');
                    $model->find($authInfo ['id']);
                    $model->login_time=time();
                    $model->login_ip=get_client_ip();
					//F('al',$authInfo ['id']);
                    $model->accesslist=serialize(RBACM::getAccessList($authInfo ['id']));
                    $model->save();
					
					//dump($authInfo);die();
					
                    session ( C ( 'USER_AUTH_KEY' ), $authInfo ['id'] );
                    session ( 'loginUserName', !empty($authInfo ['name'])?$authInfo ['name']:$authInfo['username'] );
                    session ( 'login_count', 0 );
                    if($authInfo['isadministrator']==1){
                        session ( C ( 'ADMIN_AUTH_KEY' ), true );
                    }
                    RBACM::saveAccessList();
                    
                    $this->success('登录成功', $url);
                } else {
                    $this->error($memberModel->loginError);
                }
            } else {
            }
        }
    }
    //异步登录
    public function ajaxdoLogin() {
        if ($this->_post('password') && $this->_post('username')) {
            $map['password'] = md5($this->_post('password'));
            $map['_logic'] = 'and';
            $map['site_id'] = __SITEID__;
            $map['username'] = $this->_post('username');
            $memberModel = D('Member');
            if ($memberModel->checkLogin($map)) {
                session('memberInfo', $memberModel->userInfo);
                //跳转到认证前页面
                $this->assign('info', $memberModel->userInfo);
                $authentication_DB = M('Authentication');
                $authentication = $authentication_DB->where(array(
                    'member_id' => $this->memberInfo['id']
                ))->find();
                //dump($authentication);
                $this->assign('authentication', $authentication);
                $redata['info'] = '登录成功';
                $redata['data'] = $this->fetch();
                $redata['status'] = 1;
            } else {
                $redata['info'] = $memberModel->loginError;
                $redata['status'] = 0;
                $redata['data'] = '';
            }
        } else {
            $redata['info'] = '请填写用户名和密码';
            $redata['status'] = 0;
            $redata['data'] = '';
        }
        echo json_encode($redata);
        exit();
    }
    //检查验证码
    function check_verify($code, $id = '') {
        import('@.ORG.Verify');
        $verify = new Verify();
        return $verify->check($code, $id);
    }
    //会员注册
    public function doReg() {
        if ($this->_post('username')) {
            $_POST['site_id'] = __SITEID__;
            $memberModel = D('Member');
            if (isset($_COOKIE['aff_id']) && intval($_COOKIE['aff_id']) > 0) {
                $_POST['pid'] = intval($_COOKIE['aff_id']);
            }
            $_POST['password'] = md5($_POST['password']);
            $_POST['repassword'] = md5($_POST['repassword']);
            if (!$memberModel->create()) {
                $this->error($memberModel->getError());
            }
            $user = $memberModel->where(array(
                'site_id' => __SITEID__,
                'username' => $this->_post('username')
            ))->find();
            if (is_array($user)) {
                $this->error('该用户已经被注册');
            }
            $id = $memberModel->add();
            if (false === $id) {
                $this->error($memberModel->getError());
            } else {
                $data = $memberModel->where(array(
                    'id' => $id
                ))->find();
                session('memberInfo', $data);
                
                    $this->success('注册成功', U('Intesys/Index/index'));

            }
        } else {
            $this->error('请填写信息');
        }
    }
    
	
	//发送手机证验码进行验证
	public function VerifyPhoneSend(){
		if(isset($_POST['tel'])){
			//发送验证码
			$tel = $this->_post('tel');
			if(M('Member') -> where(array('site_id' => __SITEID__,'VerifyPhone'=> 1, 'tel' => $tel)) -> find()){
				$this->error('该手机号码已经被使用！');exit;
			}
			//生成一个验证码
			$data['verifycode'] = rand(123456,999999);
			$data['tel'] = $tel;
			if(M('Member') -> where(array('site_id' => __SITEID__, 'tel' => $tel)) -> data($data) -> find()){
				$ret = M('Member') -> where(array('site_id' => __SITEID__, 'tel' => $tel)) -> data($data) -> save();
			}else{
				$data['site_id'] = __SITEID__;
				$ret = M('Member') -> data($data) -> add();
			}
			if($ret !== false){
				if(SMSSend($tel, $data['verifycode'].'　,5')){
					$this->success('发送成功，请注意查收!');exit;
				}else{
					$this->error('发送失败，请稍候重试!');exit;
				}
			}
		}
	}
	
	
    public function getcode() {
        $memberModel = D('Member');
		//exit($_GET['code']);
        $access_token = $this->weixin->getSnsAccessToken($_GET['code']);
		if(isset($_GET['state'])){
		    $statepid = explode('_and_', $_GET['state']);
		}else{
			$statepid = array(0,'');
		}//echo ($_GET['state']);exit;
		//dump($access_token);exit;
		if($this->siteInfo['is_wxLogin'] == 1){
			
            $login_result = $this->weixin->getSnsUserInfo($access_token['access_token'], $access_token['openid']);
		}else{
			
		    $login_result = $this->weixin->getUserInfo($access_token['openid']);
		}
		if($login_result === false){
			return;
		}
        $where['openid'] = $login_result['openid'];
		$where['site_id'] = __SITEID__;
        $member = $memberModel->where($where)->find();
        if ($member) {
			session('memberInfo', $member);
			session ( C ( 'USER_AUTH_KEY' ), $member ['id'] );
            //if ($member['nickname'] == '') {
                $login_result['id'] = $member['id'];
				
				if($member['isadministrator']==1){
					session ( C ( 'ADMIN_AUTH_KEY' ), true );
				}
				import ( '@.ORG.RBACM' );
				$accesslist['accesslist']=serialize(RBACM::getAccessList($member['id']));
                $memberModel -> where(array('id' => $member['id'])) -> save($accesslist);
				//F('accesslist', unserialize($accesslist['accesslist']));
				//dump($accesslist);exit;
                if ($memberModel->savewx($login_result)) {
					
					//if(__SITEID__ == 113){dump($statepid);exit;}
					if($statepid[1] != ''){
						redirect(base64_decode($statepid[1]));
                        exit();
					} 
					
                    redirect(U('Intesys/Index/index'));
                    exit();
                }
           // }
            
            if($statepid[1] != ''){
				redirect(base64_decode($statepid[1]));
				exit();
			}else {
                redirect(U('Intesys/Index/index'));
            }
        } else {
            if ($login_result) {
				
                //会员表信息
                $user['site_id'] = __SITEID__;
                $user['openid'] = $login_result['openid'];
                $user['nickname'] = parseWeixinName($login_result['nickname']);
                $user['sex'] = intval($login_result['sex']);
				$user['img_url'] = $login_result['headimgurl'];
				$user['reg_time']=time();
				
				
				if($user['img_url']){
					$user['is_subscribe'] = 1;
				}
				
				
                //插入会员
                $id = $memberModel->add($user);
				$data = array('username' => 'weixin'.$id);
				$data['pid'] = intval($statepid[0]);
				
				
				//清除推荐ID
				setcookie('aff_id', '', time()-1, '/');
				$sret = $memberModel -> updatePid($id, $data['pid']);
				
				//exit($memberModel -> getLastSql());
				//推送信息
				$userlist = $memberModel -> getUserArr($data['pid']);
				//发送通知
				
				foreach($userlist as $k => $v){
				//	sendWXMsg($v['openid'], "恭喜您！您的团队又增加了一名秘粉"); 
				}
				
                $data = $memberModel->where(array(
                    'id' => $id
                ))->find();
                session('memberInfo', $data);
               
                if ($id > 0) {
				if($statepid[1] != ''){
						redirect(base64_decode($statepid[1]));
                        exit();
					}
                    redirect(U('Intesys/Index/index'));
                } else {
                    $this->error('登陆错误');
                }
            }
        }
		exit('登录错误！获取信息错误，可能是接口密钥设置有误。');
        //$this->display();
    }
	
	   public function forget()
    {
        $check = new lwn_VerifyAction();
        
        if (IS_POST) {
            $info = $check->checkcode();
            
            if ($info['status'] == '0') {
                $this->success('验证成功', U('Public/updatePw'));
            } else {
                $this->error($info['error']);
            }
        } else {
            
            $this->display();
        }
    }

    public function updatePw()
    {
        if (IS_POST) {
            if ($_SESSION[memberInfo] != null) {
                
                $pd['password'] = md5($_POST['password']);
                
                if ($_POST['password'] != $_POST['confirm_password']) {
                    $this->error('两次输入的密码不匹配');
                }
                
                $res = M('Member')->where("site_id = " . __SITEID__ . " and username like '" . $_SESSION['memberInfo']['username'] . "'")->save($pd);
                
                if ($res > 0) {
                    session('memberInfo', NULL);
					$url=U('Public/login',['type'=>1],false,false,true);
					$this->success('修改成功',$url);
                } else {
                    session('memberInfo', NULL);
                    $this->error('修改失败，不能与旧密码相同', U('Public/forget'));
                }
            } else {
                session('memberInfo', NULL);
                $this->error('修改失败', U('Public/forget'));
            }
        } else {
            
            $this->display();
        }
    }
    
	
	
    public function getWeixinAddress() {
        Vendor('Weixin.Weixin');
        $d['token'] = getSysVal('token');
        $d['appid'] = getSysVal('appid');
        $d['appsecret'] = getSysVal('appsecret');
        $this->weixin = new WeixinChat($d);
        $this->assign('addressSign_info', $this->weixin->getSignPackage());
        //dump($this->weixin->getSignPackage());
        $this->display();
    }
}
